from com.arcfox.school.processor.base_processor import BaseProcessor
from com.arcfox.util.muilty_coroutine_util import concurrency
from com.arcfox.middleware import async_mysql_middleware as db


class YZYSchoolMajorProcessor(BaseProcessor):
    def __init__(self):
        pass

    async def parse_and_save_major_info(self, task, all_result, professional_result):
        result_list = all_result['result']
        data_list = []
        professional_result['result']
        for item in result_list:
            university_uid = task['university_uid']
            university_name = task['university_name']
            university_department = item['name']
            major_list = item['departmentMajors']
            for major in major_list:
                major_name = major['name']
                major_code = major['code']
                major_degree = major['levelText']
                country_point, province_point = self.get_point_type(major_code, professional_result)
                main_major = 0
                if country_point == 1 or province_point == 1:
                    main_major = 1
                data_list.append({
                    "university_uid": university_uid, "university_name": university_name,
                    "university_department": university_department, "major_name": major_name,
                    "major_code": major_code, "major_degree": major_degree, "is_province_point": province_point,
                    "is_nation_point": country_point, "main_major": main_major
                })

        await self.__save_major_info(tasks=data_list)

    @concurrency(5)
    async def __save_major_info(self, **params):
        task = params['task']
        mapping = db.MysqlMapping("tb_university_major")
        old_data = await mapping.query({
            "university_uid": task['university_uid'], "university_department": task['university_department'],
            "major_code": task['major_code']
        }, ['id'])
        if old_data:
            row_id = old_data[0][0]
            await mapping.update(task, {"id": row_id})
        else:
            await mapping.insert(task)

    def get_point_type(self, major_code, professional_result):
        result = professional_result['result']
        if not result or not major_code:
            return 0, 0
        countries = result['countries']
        country_point = 0
        if countries:
            matched_data = list(filter(lambda c: c['code'] == major_code, countries))
            if matched_data:
                country_point = 1
        provinces = result['provinces']
        province_point = 0
        if provinces:
            matched_data = list(filter(lambda c: c['code'] == major_code, provinces))
            if matched_data:
                province_point = 1
        return country_point, province_point

    async def parse_and_save_main_subject(self, task, result_json):
        pass
